package com.lagou.config;

import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * 解析Mybatis核心配置文件
 *
 * @author Tengfei.Wang
 * @date 26/8/2020
 */
@Slf4j
public class XmlConfigBuilder {

    public Configuration parseConfig(InputStream inputStream) {
        Configuration configuration = new Configuration();
        SAXReader saxReader = new SAXReader();
        try {
            // 解析Mybatis核心配置文件，获取数据源配置信息
            Document document = saxReader.read(inputStream);
            Element rootElement = document.getRootElement();
            Element elementDataSource = rootElement.element("dataSource");
            // 获取dataSource下的所有配置项
            List<Element> list = elementDataSource.selectNodes("//property");
            Properties properties = new Properties();
            for (Element element : list) {
                String name = element.attributeValue("name");
                String value = element.attributeValue("value");
                properties.setProperty(name, value);
            }
            log.info("dataSource info {}", properties);

            //将数据库配置信息存入c3p0数据源中，交给数据源管理
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            dataSource.setDriverClass(properties.getProperty("driverClass"));
            dataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
            dataSource.setUser(properties.getProperty("username"));
            dataSource.setPassword(properties.getProperty("password"));
            configuration.setDataSource(dataSource);

            // 获取所有配置的mapper xml文件
            Element mappers = rootElement.element("mappers");
            List<Element> mapperList = mappers.selectNodes("//mapper");
            for (Element element : mapperList) {
                String resource = element.attributeValue("resource");
                InputStream resourceAsStream = Resources.getResourceAsStream(resource);
                //解析mapper xml文件并将解析结果存入到Configuration的statementMap中
                XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(configuration);
                log.info("Parsing mapper file: {}", resource);
                xmlMapperBuilder.parse(resourceAsStream);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }

        return configuration;
    }

}
